var ns,
    // 高德定位
    bmLocation;
var app = new Vue({
    el: '#app',
    data: {
        list: [],
        donelist: [],
        form: {
            ID: 0,
            status: 0, //1-未完成 2-已完成
            StatusName: '全部',
            keywords: ''
        },
        PlanType: 3,
        total: {
            ProcessCount: 0,
            CompleteCount: 0
        },
        TabIndex: 1,
        GPSLocation: '',
        statusList: [
            { "ID": 0, "Name": "全部","count":0 },
            { "ID": 3, "Name": "未巡" ,"count":0},
            { "ID": 2, "Name": "已巡" ,"count":0},
            { "ID": 1, "Name": "异常" ,"count":0},
        ],
        // 本地文件存储key
        localKey: "",
        // 首次请求数据
        firstRequst: 0,
        // 全部的数量
        dataCount: 0,
        // 完成数量
        completeCount: 0,
        IsStartStatus:false,
        PlanStartTime:'',
    },
    methods: {
        get_data: function () {
            var that = this;
            var options = {};
            options.action = "getequipmenttaskdevicelist";
            options.ID = that.form.ID;
            options.status = that.form.status;
            options.keywords = that.form.keywords;
            options.PlanType = that.PlanType;
            // console.log(JSON.stringify(options));
            ns.post(options, function (succeed, data, err) {
                // console.log(JSON.stringify(succeed));
                // console.log(JSON.stringify(data));
                // console.log(JSON.stringify(err));
                if (succeed) {
                    that.list = data.list;
                    that.total = data.total;
                    that.statusList[0].count=that.total.ProcessCount;
                    that.statusList[1].count=that.total.UnStart;
                    that.statusList[2].count=that.total.CompleteCount;
                    that.statusList[3].count=that.total.AbnormalCount;
                   
                    //判断状态赋值
                    that.IsStartStatus=data.CanStart;
                    that.PlanStartTime=data.NextStartTime;
                    if(that.PlanStartTime){
                        that.PlanStartTime=ns.SetTime_style(that.PlanStartTime);
                    }

                   // 全部数量
                   if (that.form.status == 0)
                   that.dataCount = data.total.ProcessCount;
                   // 完成数量
                   that.completeCount = data.total.CompleteCount;
                   // 提交到服务器
                   that.pushBmLocation(true);
                    // 获取的全部数据并且还有没完成的
                    if (that.dataCount === that.completeCount) {
                        // 任务全部完成
                        // 清除循环定位的定时器
                        clearInterval(bmlocationTimer);
                        // 停止定位
                        bmLocation.stopLocation();
                    };
                    that.firstRequst += 1;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_open_scan: function (item) {
            var that = this;
            ns.confirmPer('camera', function () {
                setTimeout(function () {
                    that.do_open_scan_start(item);
                }, 200)
            })
        },
        do_open_scan_start: function (item) {
            var that = this;
            ns.openFrame('scanner_frm', {
                type: 3,
                id: item.ID,
                EncriptID: item.EncriptID
            });
        },
        open_details: function (item) {
            ns.openWin('patrolplan_details_frm', '巡更点检查', {
                id: item.ID
            });
        },
        select_status: function (e) {
            // this.TabIndex = status;
            this.form.status = e.target.value;
            this.get_data();
        },
        onClickStatus:function(item){
            var that = this;
            that.form.status = item.ID;
            that.get_data();
        },
        do_view: function (item,index) {
            var that = this;
            //增加判断提示  当前线路需要按顺序执行巡查，请先完成对应巡查点。
            if (item.TaskStatus != 3) {
                if(!item.CanPunchCard){
                    api.toast({
                        msg: '当前线路未开始或需要按顺序执行巡查，请先完成对应巡查点。',
                        duration: 4000,
                        location: 'bottom'
                    });
                    return;
                }
                if(item.RequireScan){
                    that.do_open_scan(item);
                    return;
                }        
            }
            if (item.TaskStatus == 3) {
                if(item.IsMiss&&item.IsAllowCard&&item.RequireScan){
                    that.do_open_scan(item);
                    return;
                }
            }
            that.open_details(item);
        },
        do_search: function () {
            var that = this;
            that.get_data();
        },
        check_scan_result: function (id) {
            var that = this;
            if(that.IsStartStatus){
                api.toast({
                    msg: '任务未开始,暂时不能进行扫码操作喔',
                    duration: 4000,
                    location: 'bottom'
                });
                return;
            }
            if (!id) {
                ns.openFrame('scanner_frm', {
                    type: 10
                });
            }
            else {
                
                var options = {};
                options.action = "qrcoderesult";
                options.ID = that.form.ID;
                options.QRCode = id;
                ns.post(options, function (succeed, data, err) {
                    // console.log(JSON.stringify(data));
                    // console.log(JSON.stringify(err));
                    if (succeed) {
                        // 接口判断，如果成功后跳转详情页
                        ns.openWin('patrolplan_details_frm', '巡更点检查', {
                            id: data.TaskID
                        });
                    } else if (err) {
                        api.toast({
                            msg: err,
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                });

            };
        },
        // 初始化bmLocation
        initBmLocation() {
            let that = this;
            ns.confirmPer('location', function () {
                bmLocation.configManager({
                    accuracy: 'tenMeters',
                    filter: 1
                }, function(ret, err) {
                    if (ret.status) {
                        // 禁止屏幕休眠
                        // api.setKeepScreenOn({
                        //     keepOn: true
                        // });
                        that.bmLocationStart();
                    };
                });
            });
        },
        // 开始定位并存储到本地
        bmLocationStart() {
            let that = this;
            var param = { accuracy: 100, filter: 1, autoStop: false };
            bmLocation.startLocation(function (ret, err) {
                if (ret.status) {
                    let log = ret.lon,
                    lat = ret.lat,
                    bmData = {
                        longitude: log,
                        latitude: lat
                        // dateTime:parseInt(new Date().getTime()/1000)
                    },
                    locationDataArr = that.getprefData();
                    locationDataArr.push(bmData);
                    api.setPrefs({
                        key: that.localKey,
                        value: JSON.stringify(locationDataArr)
                    });

                } else {
                }
            });
        },
        //获取本地存储经纬度
        getprefData() {
            let bmlocationDataArr = [],
                bmLocationDataStr = api.getPrefs({
                    sync: true,
                    key: this.localKey
                });
            if (bmLocationDataStr) bmlocationDataArr = JSON.parse(bmLocationDataStr);
            return bmlocationDataArr;
        },
        // 本地数据上传到数据库
        pushBmLocation(isInit = true) {
            let that = this;
            let dataArr = that.getprefData();
            // dataArr.splice(0, 3);
            if (dataArr.length === 0) {
                api.removePrefs({
                    key: that.localKey
                });
                if (isInit) that.initBmLocation();
            }
            else {
                pushObj = {
                    ID: that.form.ID,
                    bmlocation: JSON.stringify(dataArr),
                    action: "savebmlocation"
                };
                ns.post(pushObj, function (succeed, data, err) {
                    if (succeed) {
                        api.removePrefs({
                            key: that.localKey
                        });
                    };
                    if (isInit) that.initBmLocation();
                }, {
                    toast: false
                });
            };
        },
        onDealTaskTime:function(time){
            return ns.SetTime_style(time)
        },
    }
});
apiready = function () {
    api.parseTapmode();
    ns = window.Foresight.Util;
    app.form.ID = api.pageParam.id || 0;
    // 本地存储key
    app.localKey = "bmLocation" + app.form.ID;
    toast = new auiToast();
    // 引入aMapLBS定位
    // bmLocation = api.require('aMapLocation');
    bmLocation = api.require('aMapLBS');
    bmLocation.updateLocationPrivacy({
        privacyAgree:'didAgree',
        privacyShow:'didShow',
        containStatus:'didContain'
    });
    
    setTimeout(function () {
        app.get_data();
    }, 500);
    api.addEventListener({
        name: 'devicetaskcomplete'
    }, function (ret, err) {
        app.get_data();
    });
    ns.init_search();
    api.addEventListener({
        name: 'scandeviceqrcodedone'
    }, function (ret, err) {
        app.check_scan_result(ret.value.id);
    });
}
